<!--
 * @Description: description
 * @version: 0.1
 * @Author: youhuimin
 * @Date: 2021-08-19 18:04:48
 * @LastEditors: youhuimin
 * @LastEditTime: 2021-09-07 18:05:45
 * @FilePath: \xdeas-user-web\src\components\roomTree\leftTree.vue
-->
<template>
  <div>
    <ul class="all-list tree_item_box">
      <li
        v-for="(item, i) in list"
        :key="item.id"
        :id="'id' + item.id"
        class="linkLine_default"
        :class="{
          linkLine_first: (i === 0) & (list.length > 1),
          after_none: i === 0 && list.length === 1,
          linkLine_last: i === list.length - 1 && i !== 0,
        }"
      >
        <span
          class="linkLine_last-l"
          :style="{
            height: height,
          }"
          v-if="i === list.length - 1 && isInit && item.name"
        >
        </span>
        <div
          class="tree-item expend pointer second_layer"
          :class="{
            'bg-white': isInclude(item.id),
            'hide-before': item.parentId == '0',
            'hover-active': isAbleValue(item.id),
          }"
          @click="changeActive(item, i)"
        >
          <a-checkbox
            style="margin-right:8px"
            :disabled="unableValue.includes(item.id)"
            :checked="curValue.includes(item.id)"
            v-if="type == 'checkbox'"
            @click.stop="isAbleValue(item.id) && setValue(item.id)"
          >
          </a-checkbox>
          <img v-if="item.showImg" class="mr-8 wh18" :src="localImg" alt="" />
          <span class="content flex-c flex-jsb">
            <span class="ellipsis-2 flex-1">
              {{ item.name }}
            </span>
            <template v-if="item.subRooms && item.subRooms.length > 0">
              <div class="relative">
                <img
                  :src="rightImg"
                  class="wh12 right"
                  :class="{ rotate90: openArr.includes(i) }"
                  @click.stop="toggle(i)"
                />
              </div>
            </template>
          </span>
        </div>

        <!-- 递归 -->
        <div v-show="openArr.includes(i)" v-if="item.subRooms && item.subRooms.length">
          <leftTree
            class="item"
            :list="item.subRooms"
            :unableValue="unableValue"
            :default-expand="defaultExpand"
            v-model="curValue"
            @change="handleChange"
            :type="type"
            :ref="'treeItem' + i"
            :max="max"
          ></leftTree>
        </div>
      </li>
      <!-- <span class="all-list_line" :style="{ height: lineHeight() }"></span> -->
    </ul>
  </div>
</template>

<script>
const localImg = require("@/assets/images/electricMonitor/local.png");
const rightImg = require("@/assets/images/electricMonitor/right.png");
export default {
  name: "leftTree",
  data() {
    return {
      openArr: [],
      checkboxIds: [],
      curValue: [],
      localImg,
      rightImg,
      isInit: false,
      height: "24px",
    };
  },
  props: {
    list: {
      type: Array,
    },
    defaultExpand: {},
    value: {
      type: Array,
    },
    type: {
      type: String,
      default: "radio", //单选radio或多选checkbox
    },
    unableValue: {
      type: Array,
      default: () => {
        return [];
      },
    },
    max:{},
  },
  watch: {
    value: function(val) {
      this.curValue = val;
    },
    defaultExpand: function(val) {
      this.setDefaultExpand(val);
    },
  },
  methods: {
    isInclude(id) {
      return this.curValue.indexOf(id) > -1;
    },
    toggle(i) {
      if (this.openArr.includes(i)) {
        let index = this.openArr.indexOf(i);
        this.openArr.splice(index, 1);
      } else {
        this.openArr.push(i);
        this.$nextTick((_) => {
          this.$refs["treeItem" + i][0] &&
            this.$refs["treeItem" + i][0].setLineHeight();
        });
      }
    },
    // 当前项是否可点击
    isAbleValue(id) {
      return this.unableValue.indexOf(id) == -1;
    },
    // 找到子元素在父元素中的相对位置
    getElementTop(element) {
      var el =
        typeof element == "string" ? document.getElementById(element) : element;

      if (el.parentNode === null || el.style.display == "none") {
        return false;
      }

      return el.offsetTop - el.parentNode.offsetTop;
    },
    lineHeight() {
      let h = `calc( 100% - 24px)`;
      this.$nextTick((_) => {
        let len = this.list.length;
        h = this.openArr.includes(len - 1)
          ? this.getElementTop("id" + this.list[len - 1].id)
          : `calc( 100% - 24px)`;
        return h;
      });
    },
    changeActive(item, i) {
      if (item.subRooms && item.subRooms.length > 0) {
        this.toggle(i);
      }
      if (this.unableValue.indexOf(item.id) == -1) {
        this.setValue(item.id);
      }
    },
    setValue(id) {
      if (this.type == "checkbox") {
        if (this.curValue.includes(id)) {
          let index = this.curValue.indexOf(id);
          this.curValue.splice(index, 1);
        } else {
          if(this.max && this.max > this.curValue.length){
            this.curValue.push(id);
          }
        }
      } else {
        this.curValue = [id];
      }
      this.$emit("update:value", this.curValue);
      this.$emit("change", {
        value: this.curValue,
        obj: this.list.filter((v) => {
          return this.curValue.indexOf(v.id) > -1;
        }),
      });
      this.$forceUpdate();
      console.log("left-tree==> curValue=", this.curValue);
    },
    handleChange({ value, obj }) {
      this.curValue = value;
      this.$emit("update:value", value);
      this.$emit("change", { value, obj });
      this.$forceUpdate();
    },
    setDefaultExpand(val) {
      let arr = [];
      this.list.forEach((v, i) => {
        if (val.includes(v.id)) {
          arr.push(i);
        }
      });
      this.openArr = arr;
    },
    setLineHeight() {
      if (this.list.length) {
        let item = this.list[this.list.length - 1];
        this.height = this.getElementH(`id` + item.id);
        // console.log(this.height,item.name)
      }
    },
    getElementH(eId) {
      if (!eId) {
        return 0;
      }
      let element = document.getElementById(eId);
      // console.log(element)
      let itemEle = document.querySelector(`#${eId} .tree-item`); // tree-item高度
      // console.log(itemEle)
      if (!element || !itemEle) {
        return "";
      }
      let h = itemEle.offsetHeight / 2 + itemEle.offsetTop;
      return (h < 24 ? 24 : h) + "px";
    },
    toggleAll(flag,isFirst = ''){
      let treesRef = this.list.map((v,i)=>{
        return this.$refs['treeItem' + i]
      })
      treesRef.forEach(v=>{
        v && v[0] && v[0].toggleAll(flag)
      })
      if(flag || isFirst){
        // 开启全部
        this.openArr = this.list.map((v,i)=>{
          return i
        })
      }else{
        this.openArr = []
      }
    }
  },
  created() {
    this.isInit = false;
  },
  mounted() {
    this.curValue = this.value;
    this.setDefaultExpand(this.defaultExpand);
    this.isInit = true; //是否初始化完成
    this.$nextTick((_) => {
      setTimeout((_) => {
        this.setLineHeight();
      }, 0);
    });
  },
};
</script>
<style lang="less" scoped>
.c-C0C4CC {
  color: #c0c4cc;
}
.wh18 {
  width: 18px;
  height: 18px;
}
.wh12 {
  width: 12px;
  height: 12px;
}
i {
  line-height: 0;
  img {
    width: 16px;
    height: 16px;
  }
}
.item {
  padding-left: 4px;
}
.bold {
  font-weight: bold;
}
.after_none::after {
  display: none;
}
ul {
  line-height: 1.5em;
  list-style-type: none;
  white-space: nowrap;
  position: relative;
}
li {
  list-style-type: none;
  padding: 4px;
  padding-right: 0;
  user-select: none;
}

li:nth-last-child(1) {
  padding-bottom: 0;
}

li:nth-child(1) {
  padding-top: 8px;
}

.tree-item {
  display: flex;
  align-items: center;
  border-radius: 4px;
  line-height: 20px;
  border: 1px solid #e4e7ed;
  padding: 8px 12px;
  transition: all 0.2s linear;
}

// .expend {
//   position: relative;
// }

// .expend::before {
//   content: "";
//   position: absolute;
//   width: 6px;
//   left: 9px;
//   top: 50%;
//   border-top: 1px dotted #c3c5c8;
// }
.hide-before::before {
  display: none;
}
.rotate90 {
  transform: rotate(90deg);
  -ms-transform: rotate(90deg); /* IE 9 */
  -moz-transform: rotate(90deg); /* Firefox */
  -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
  -o-transform: rotate(90deg); /* Opera */
}
/deep/ .tree-item .ant-checkbox-disabled .ant-checkbox-inner {
  background-color: #E4E7ED !important;
  border-color: #DDDFE6 !important;
}

// .item .expend::before {
//   content: "";
//   position: absolute;
//   width: 18px;
//   left: -18px;
//   top: 16px;
//   border-top: 1px solid #e4e7ed;
// }

.item .all-list .all-list_line {
  position: absolute;
  width: 1px;
  height: calc(100% - 24px);
  left: 6px;
  top: 0;
  border-left: 1px solid #e4e7ed;
  border-radius: 50% 0 0;
}

// .item ul {
//   padding-left: 1.4em;
// }
.ellipsis-2 {
  overflow: hidden;
  display: -webkit-box; //将对象作为弹性伸缩盒子模型显示;
  text-overflow: ellipsis; //溢出部分用省略号代替
  -webkit-line-clamp: 2; //设置文本显示两行
  -webkit-box-orient: vertical; //从上到下排列子元素;
  white-space: normal;
}
.content {
  padding-left: 4px;
  transition: all 0.1s linear;
  width: 100%;
}
.spacing {
  display: inline-block;
  width: 18.5px;
  height: 1em;
}
.right {
  transition: all 0.1s linear;
}
.bg-white {
  background-color: #fff;
}
.hover-active:hover {
  background-color: #fff;
}
.tree_item_box {
  position: relative;
  width: 100%;
  cursor: pointer;
}
.item {
  ul {
    padding-left: 1.4em;
  }
  li {
    position: relative;
  }
  .linkLine_default::after {
    content: "";
    position: absolute;
    height: 100%;
    width: 1px;
    left: -11px;
    top: 0px;
    background: #e4e7ed;
  }

  .second_layer {
    position: relative;
    width: 100%;
    cursor: pointer;
  }
  .third_layer {
    position: relative;
    width: 100%;
    color: #999999;
  }

  .second_layer::before {
    content: "";
    position: absolute;
    height: 1px;
    width: 16px;
    left: -16px;
    top: 50%;
    background: #e4e7ed;
  }
  .third_layer::before {
    content: "";
    position: absolute;
    height: 1px;
    width: 22px;
    left: 9px;
    top: 9px;
    background: #e4e7ed;
  }
  .linkLine_first::after {
    content: "";
    position: absolute;
    /* 为了触顶 */
    top: 0;
    height: 100%;
    width: 1px;
    left: -11px;
    background: #e4e7ed;
  }
  // 上半截
  .linkLine_half_top::after {
    content: "";
    position: absolute;
    height: calc(50% + 4px);
    top: 0px;
    width: 1px;
    left: -11px;
    background: #e4e7ed;
  }
  .linkLine_last::after {
    display: none;
  }
  .linkLine_last-l {
    display: inline-block;
    position: absolute;
    height: 27px;
    width: 1px;
    left: -11px;
    top: 0px;
    background: #e4e7ed;
  }
}
</style>
